// require('regenerator-runtime');
import { 
  getAccessByCompany,
  getIdByName,
  login,
  log,
  getUserInfo
} from "../../utils/api/common-api.js"
import { judgeMyApi } from "../../utils/util/index";

import {
  isLogin,
  loginByWx,
} from "@ray-js/wechat";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    username:'',
    account:'',
    password:'',
    usernameError:'',
    accountError:'',
    passwordError:'',
    toast:'',
    isLogin: false,// 微信登录状态
    list: [
      // {
      //   name: '基础业务功能',
      //   url: '/packageA/base_function/index',
      // },
      // {
      //   name: '体验 Demo 面板',
      //   url: '/packageA/home_center/device_list/index',
      // },
      // {
      //   name: '体验涂鸦小程序',
      //   url: 'navigateToMiniProgram',
      // },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const username =  wx.getStorageSync('username')
    if(username){
      log("获取缓存:"+username, JSON.stringify(username),'登录页面');
    }else{
      log("获取不到本地缓存公司名");
    }
    this.setData({username})
  },
  /***
   * 进入页面先判断有没有登录，没有的话先登录
   */
  async onShow() {
    const hasLogin = await isLogin();
    this.setData({
      isLogin: hasLogin,
    });
    if (!hasLogin) {
      this.wxLogin();
    }
    const user = await getUserInfo() || 0;
    this.setData({uid:user.uid})
    log("登录用户", JSON.stringify(user), user.uid);
    this.isSaasLogin()
  },
  /**
   * 封装好的微信登录
   * @returns
   */
  wxLogin: async function () {
    let canIuse = await judgeMyApi({
      myApi: "getUserProfile",
      myVersion: "2.24.0",
    });
    console.log("canIuse微信环境接口", canIuse);
    log("canIuse微信环境接口:", JSON.stringify(canIuse), this.data.uid);
    if (!canIuse) return false;
    wx.showLoading({
      title: "正在登陆",
    });
    try {
      await loginByWx();
      wx.showToast({
        title: "登录成功",
        duration: 1000,
      });
      this.setData({
        isLogin: true,
      });
      this.isSaasLogin()
    } catch (error) {
      console.log(error);
      log("微信登陆失败:", JSON.stringify(error), this.data.uid);
      wx.showToast({
        title: "登录失败",
        icon: "error",
        duration: 1000,
      });
    } finally {
      wx.hideLoading();
    }
  },
  /**
   * 如果微信+saas都登录，直接跳转到搜索页
   */
  isSaasLogin: async function () {
    const userInfo = wx.getStorageSync('userInfo')
    const {expiresTime,accessToken} = userInfo;
    const curTimeStamp = new Date().getTime();
    console.log(`当前时间戳：${curTimeStamp}`,`失效时间戳：${expiresTime}`)
    if(curTimeStamp > expiresTime && !accessToken){
      return
    }
    const username = wx.getStorageSync("username")
    username && this.gotoOtherage(username)
  },
  usernameChange:function(e){
    const username =  e.detail;
    console.log(e,e.detail)
    log('监听公司名改变',e.detail,'登录页面');
    this.setData({username})
    if(!username){
      this.setData({usernameError:'请输入公司名'})
    } else {
      this.setData({usernameError:'',toast:''})
    }
  },
  accountChange:function(e){
    const account =  e.detail;
    console.log(e,e.detail)
    log('监听账号改变',e.detail,'登录页面');
    this.setData({account})
    if(!account){
      this.setData({accountError:'请输入用户名'})
    } else {
      this.setData({accountError:'',toast:''})
    }
  },
  passwordChange:function(e){
    const password =  e.detail;
    console.log('监听密码',e,e.detail)
    log('监听密码改变',e.detail,'登录页面');
    this.setData({password})
    if(!password){
      this.setData({passwordError:'请输入密码'})
    } else {
      this.setData({passwordError:'',toast:''})
    }
  },
  tenantLogin:async function () {
    console.log(this.data)
    log('点击登录按钮',JSON.stringify(this.data),'登录页面');
    const {username,account,password} = this.data;
    console.log(username)
    console.log(account)
    console.log(password)

    if(!username || !account || !password){
      !username && this.setData({usernameError:'请输入公司名'})
      !account && this.setData({accountError:'请输入用户名'})
      !password && this.setData({passwordError:'请输入密码'})
      return
    }

    if(username){
      log("用户点击登录按钮公司名:"+username, JSON.stringify( {username,account,password}),'登录页面');
    }
    let params = {
      "tenantName":username,"username":account,"password":password,"rememberMe":true
    }

    console.log(params)
    try{
    getAccessByCompany(username).then(async tenantInfo=> {
      console.log(tenantInfo)
      wx.setStorageSync("tenantInfo",tenantInfo)
      const res = await login(params)
      console.log(res)
      if(!res.data){
        this.setData({toast:res.msg})
        return
      }
      log(`参数【${username}】获取到后端返回配置：`, JSON.stringify(tenantInfo),'登录页面');
      log(`解析【${username}】返回jsonContent：`, tenantInfo.jsonContent,'登录页面');
      wx.setStorageSync("userInfo",res.data)
      wx.setStorageSync("username",username)
      this.gotoOtherage(username)

    })
    }catch(e){
      console.log('catch',e)
    }
  },
  gotoOtherage: function (username) {
    console.log(this.data.username)
    console.log("点击登录跳转地址:", `/packageA/pages/index/index?id=${username}`,'登录页面');
    wx.redirectTo({
      url: `/packageA/pages/index/index?id=${username}`,
    })
  },
});
